package com.smatiger.hotdeploy.loader.core;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.smatiger.hotdeploy.loader.constants.Constants;

/**
* @Description: 自定简单类加载器
* @author smatiger
* @date 2017年6月27日 下午5:51:10 
*/
public class SimpleClassLoader implements IClassLoader {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ClassLoader createClassLoader(ClassLoader parentClassLoader, String... paths) {
        if (paths == null) {
            throw new RuntimeException("paths cannot be empty!");
        }
        List<URL> urlList = Lists.newArrayList();
        for (String path : paths) {
            List<File> jarFileList = scanJarFile(path);
            if (CollectionUtils.isEmpty(jarFileList)) {
                logger.info("path:{} is empty!", path);
                continue;
            }
            for (File file : jarFileList) {
                if (!file.exists() || !file.isFile()) {
                    continue;
                }
                URL fileURL = null;
                try {
                    fileURL = file.toURI().toURL();
                } catch (MalformedURLException e) {
                    logger.error("file:{} to URL faild!", file.getPath(), e);
                }
                if (fileURL != null) {
                    urlList.add(fileURL);
                }
            }
        }
        URL[] urls = new URL[urlList.size()];
        urlList.toArray(urls);
        return new URLClassLoader(urls, parentClassLoader);
    }

    private List<File> scanJarFile(String path) {
        File folder = new File(path);
        if (!folder.isDirectory()) {
            return null;
        }
        List<File> jars = Lists.newArrayList();
        for (File file : folder.listFiles()) {
            if (!file.isFile()) {
                continue;
            }
            String fileName = file.getName();
            if (StringUtils.isBlank(fileName)) {
                continue;
            }
            if (fileName.toUpperCase().endsWith(Constants.JAR_FILE_SUFFIX)) {
                jars.add(file);
            }
        }
        return jars;
    }
}
